const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const scoreElement = document.getElementById('score');

const gridSize = 20;
const tileCount = canvas.width / gridSize;

// 预加载图片
const snakeHeadImg = new Image();
const snakeBodyImg = new Image();
const foodImg = new Image();

// 使用新的蛇头 SVG（更现代的设计）
snakeHeadImg.src = 'data:image/svg+xml;charset=UTF-8,' + encodeURIComponent(`
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
    <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2z" fill="#4CAF50"/>
    <path d="M12 4c4.41 0 8 3.59 8 8s-3.59 8-8 8-8-3.59-8-8 3.59-8 8-8z" fill="#66BB6A"/>
    <circle cx="9" cy="10" r="1.5" fill="#FFF"/>
    <circle cx="15" cy="10" r="1.5" fill="#FFF"/>
    <circle cx="9" cy="10" r="0.5" fill="#000"/>
    <circle cx="15" cy="10" r="0.5" fill="#000"/>
    <path d="M12 14c-2 0-3 1-3 1s1.5 1 3 1 3-1 3-1-1-1-3-1z" fill="#388E3C"/>
</svg>`);

snakeBodyImg.src = 'https://api.iconify.design/material-symbols:circle.svg?color=%234CAF50&width=18&height=18';
foodImg.src = 'https://api.iconify.design/emojione:red-apple.svg?width=20&height=20';

let snake = [
    { x: 10, y: 10 },
];
let food = { x: 15, y: 15 };
let dx = 0;
let dy = 0;
let score = 0;
let gameSpeed = 150; // 初始速度更慢
let gameInterval = null;
let isPaused = true;
let currentLevel = 1;

// 难度设置
const levels = {
    1: { speed: 150, scoreThreshold: 50 },
    2: { speed: 120, scoreThreshold: 100 },
    3: { speed: 100, scoreThreshold: 200 },
    4: { speed: 80, scoreThreshold: 300 },
    5: { speed: 60, scoreThreshold: Infinity }
};

// 检查并更新难度
function updateDifficulty() {
    const nextLevel = currentLevel + 1;
    if (levels[nextLevel] && score >= levels[currentLevel].scoreThreshold) {
        currentLevel = nextLevel;
        changeGameSpeed(levels[currentLevel].speed);
        showLevelUpMessage();
    }
}

// 更改游戏速度
function changeGameSpeed(newSpeed) {
    gameSpeed = newSpeed;
    if (gameInterval) {
        clearInterval(gameInterval);
        gameInterval = setInterval(gameLoop, gameSpeed);
    }
}

// 显示等级提升消息
function showLevelUpMessage() {
    const message = document.createElement('div');
    message.textContent = `升级！当前等级 ${currentLevel}`;
    message.style.cssText = `
        position: fixed;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        background: rgba(76, 175, 80, 0.9);
        color: white;
        padding: 20px;
        border-radius: 10px;
        font-size: 24px;
        animation: fadeOut 2s forwards;
        z-index: 1000;
    `;
    document.body.appendChild(message);
    setTimeout(() => message.remove(), 2000);
}

// 绘制蛇
function drawSnake() {
    snake.forEach((segment, index) => {
        const x = segment.x * gridSize;
        const y = segment.y * gridSize;
        
        if (index === 0) {
            // 计算蛇头旋转角度
            let rotation = 0;
            if (dx === 1) rotation = 0;
            else if (dx === -1) rotation = 180;
            else if (dy === -1) rotation = 270;
            else if (dy === 1) rotation = 90;
            
            ctx.save();
            ctx.translate(x + gridSize/2, y + gridSize/2);
            ctx.rotate(rotation * Math.PI / 180);
            // 调整蛇头大小，使其略大于身体部分
            ctx.drawImage(snakeHeadImg, -gridSize*0.6, -gridSize*0.6, gridSize*1.2, gridSize*1.2);
            ctx.restore();
        } else {
            // 身体部分保持不变
            ctx.drawImage(snakeBodyImg, x + 1, y + 1, gridSize - 2, gridSize - 2);
        }
    });
}

// 绘制食物
function drawFood() {
    ctx.drawImage(foodImg, food.x * gridSize, food.y * gridSize, gridSize, gridSize);
}

// 生成新的食物位置
function generateFood() {
    let newFood;
    do {
        newFood = {
            x: Math.floor(Math.random() * tileCount),
            y: Math.floor(Math.random() * tileCount)
        };
    } while (snake.some(segment => segment.x === newFood.x && segment.y === newFood.y));
    food = newFood;
}

// 更新游戏状态
function update() {
    const head = { x: snake[0].x + dx, y: snake[0].y + dy };
    
    // 检查是否撞墙
    if (head.x < 0 || head.x >= tileCount || head.y < 0 || head.y >= tileCount) {
        gameOver();
        return;
    }
    
    // 检查是否撞到自己
    for (let i = 1; i < snake.length; i++) {
        if (head.x === snake[i].x && head.y === snake[i].y) {
            gameOver();
            return;
        }
    }
    
    snake.unshift(head);
    
    // 检查是否吃到食物
    if (head.x === food.x && head.y === food.y) {
        score += 10;
        scoreElement.textContent = score;
        generateFood();
        updateDifficulty();
    } else {
        snake.pop();
    }
}

// 游戏主循环
function gameLoop() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    update();
    drawFood();
    drawSnake();
}

// 游戏结束处理
function gameOver() {
    clearInterval(gameInterval);
    alert(`游戏结束！\n最终得分：${score}\n达到等级：${currentLevel}`);
    resetGame();
}

// 重置游戏
function resetGame() {
    snake = [{ x: 10, y: 10 }];
    dx = 0;
    dy = 0;
    score = 0;
    currentLevel = 1;
    gameSpeed = levels[1].speed;
    scoreElement.textContent = score;
    generateFood();
    isPaused = true;
    if (gameInterval) {
        clearInterval(gameInterval);
        gameInterval = null;
    }
}

// 处理按键输入
document.addEventListener('keydown', (e) => {
    if (e.key === ' ') {
        if (isPaused) {
            isPaused = false;
            if (!gameInterval) {
                gameInterval = setInterval(gameLoop, gameSpeed);
            }
        } else {
            isPaused = true;
            if (gameInterval) {
                clearInterval(gameInterval);
                gameInterval = null;
            }
        }
        return;
    }

    if (!isPaused) {
        switch (e.key.toLowerCase()) {
            case 'i': // 上
                if (dy !== 1) {
                    dx = 0;
                    dy = -1;
                }
                break;
            case 'k': // 下
                if (dy !== -1) {
                    dx = 0;
                    dy = 1;
                }
                break;
            case 'j': // 左
                if (dx !== 1) {
                    dx = -1;
                    dy = 0;
                }
                break;
            case 'l': // 右
                if (dx !== -1) {
                    dx = 1;
                    dy = 0;
                }
                break;
        }
    }
});

// 初始化游戏
resetGame();
drawSnake();
drawFood();

// 更新控制面板显示
const controlsDiv = document.querySelector('.controls p');
controlsDiv.innerHTML = `
    上移: <span class="key">I</span>
    下移: <span class="key">K</span>
    左移: <span class="key">J</span>
    右移: <span class="key">L</span>
    <br><span class="key space">空格</span> 开始/暂停
    <br><span class="level-info">当前等级: 1</span>
`; 